const NewMaterial = require('NewMaterial');

cc.Class({
    extends: cc.Component,

    properties: {
        target: {
            default: null,
            type: cc.Sprite,
        },
        shaderFile: {
            default: "",
            type: cc.String,
            tooltip: "shader定义文件"
        },
        flipY: {
            default: false,
            type: cc.Boolean,
            tooltip: "反转纹理Y轴"
        }
    },

    onLoad () {
        if (this.target===null) {
            this.target = this.node.getComponent(cc.Sprite);
        }
        if (this.shaderFile.length>0) {
            if (this.shaderFile.length>3 && this.shaderFile.charAt(this.shaderFile.length-3)=="." && this.shaderFile.charAt(this.shaderFile.length-2)=="j" && this.shaderFile.charAt(this.shaderFile.length-1)=="s") {
                this.shaderFile = this.shaderFile.substring(0, this.shaderFile.length-3);
            }
            cc.dynamicAtlasManager.enabled = false;
            this._material = new NewMaterial(this.shaderFile);
        }
    },

    start () {
        if (this.target) {
            let texture = this.target.spriteFrame.getTexture();
            this._material.setTexture(texture, this.flipY);
            this._material.updateHash();
            this.target._material = this._material;
            this.target._renderData._material = this._material;
        }
    },
});
